-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
82 lines (65 loc) · 1.69 KB
/
Solution.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
Node(int value) : data(value), next(nullptr) {}
};
void printList(Node* head) {
while (head) {
cout << head->data << " -> ";
head = head->next;
}
cout << "NULL" << endl;
}
bool detectAndRemoveCycle(Node* head) {
Node *slow = head, *fast = head;
// Detect Cycle
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) break;
}
if (!fast || !fast->next) return false; // No cycle
// Remove Cycle
slow = head;
while (slow->next != fast->next) {
slow = slow->next;
fast = fast->next;
}
fast->next = nullptr; // Break the cycle
return true;
}
int main() {
int n, value, cyclePosition;
cout << "Enter the number of nodes: ";
cin >> n;
Node *head = nullptr, *tail = nullptr, *cycleNode = nullptr;
for (int i = 0; i < n; i++) {
cout << "Enter value for node " << i + 1 << ": ";
cin >> value;
Node* newNode = new Node(value);
if (!head) {
head = tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
if (i == cyclePosition - 1) {
cycleNode = newNode;
}
}
cout << "Enter the position to create a cycle (0 for no cycle): ";
cin >> cyclePosition;
if (cyclePosition > 0) {
tail->next = cycleNode;
}
if (detectAndRemoveCycle(head)) {
cout << "Cycle detected and removed." << endl;
} else {
cout << "No cycle detected." << endl;
}
cout << "Updated List: ";
printList(head);
return 0;
}